package com.lagou.edu.user.service;

import com.lagou.edu.user.client.CodeClient;
import com.lagou.edu.user.entity.TokenDO;
import com.lagou.edu.user.entity.UserDO;
import com.lagou.edu.user.mapper.TokenMapper;
import com.lagou.edu.user.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import java.util.Objects;
import java.util.Optional;
import java.util.UUID;

/**
 * @author liangzj
 * @date 2021/6/23 22:31
 */
@Service
public class UserService {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private TokenMapper tokenMapper;

    public boolean addUser(String email, String password) {
        UserDO user = new UserDO();
        user.setEmail(email);
        user.setPassword(password);
        return userMapper.insert(user) == 1;
    }

    public String createToken(String email) {
        TokenDO tokenDO = new TokenDO();
        tokenDO.setEmail(email);
        tokenDO.setToken(UUID.randomUUID().toString());
        tokenMapper.insert(tokenDO);

        return tokenDO.getToken();
    }

    public boolean existEmail(String email) {
        UserDO user = userMapper.selectByEmail(email);
        return Objects.nonNull(user);
    }

    public UserDO getUser(String email, String password) {
        return userMapper.selectByEmailAndPassword(email, password);
    }

    public UserDO getUser(String token) {
        TokenDO tokenDO = tokenMapper.select(token);
        Assert.notNull(tokenDO, "用户未登录！");

        return Optional
                .ofNullable(userMapper.selectByEmail(tokenDO.getEmail()))
                .orElseThrow(() -> new IllegalArgumentException("用户信息未找到！"));
    }

}
